package com.peanut.baby.widget;

import android.content.Context;

import android.util.AttributeSet;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.tencent.mars.xlog.Log;

public class AutoSwitchViewPager extends ViewPager {


    long duration = 2000;
    boolean playing = false;
    PagerAdapter adapter;
    public AutoSwitchViewPager(@Nullable Context context) {
        this(context, null);
    }

    public AutoSwitchViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

    }


    @Override
    public void setAdapter(@Nullable PagerAdapter adapter) {
        this.adapter = adapter;
        super.setAdapter(adapter);
    }


    /**
     * 开始自动播放
     * @param displayTime : 页面显示时间
     */
    public void startPlay(int displayTime) {

        this.duration =  displayTime;
        if (adapter == null || adapter.getCount() <= 1)
            return;

        stopPlay();
        playing = true;
        postDelayed(player, this.duration);
    }

    /**
     * 停止播放
     */
    public void stopPlay() {
        removeCallbacks(player);
       playing = false;
    }


    // 循环播放消息
    private final Runnable player = new Runnable() {

        @Override
        public void run() {
            if (playing) {
                int currentIndex = getCurrentItem();
                if(currentIndex == adapter.getCount() - 1){
                    currentIndex = 0;
                }else{
                    currentIndex ++;
                }
                setCurrentItem(currentIndex,true);
                postDelayed(player, duration);
            }
        }
    };


}
